<?php
// +----------------------------------------------------------------------
// | Description: 消费总和统计 - BillSum
// +----------------------------------------------------------------------
// | Author: liaoyizhi <liaoyizhi@gmail.com>
// +----------------------------------------------------------------------
// | Update: Markus <i@yoyoyo.me>
// +----------------------------------------------------------------------

namespace codelord\finance\model;
use think\Exception;

class BillSum extends \think\Model {
    /**
     * 从bill_sum表中检测消费各类别数据
     * @param  int   $uid         用户的id主键号
     * @param  int   $currency_id 货币id
     * @return array 返回用户的消费记录
     */
    public function getBillSum(int $uid,int $currency_id) : ? BillSum
    {
        $result = $this->field('currency_id, COALESCE(SUM(sum),0) as sum, COALESCE(SUM(lock_sum),0) AS lock_sum')
            ->where([
                'uid'           =>  $uid,
                'currency_id'   =>  $currency_id
            ])
            ->select();
        return $result[0];
    }

    /**
     * 更新各货币变化总和
     * @param array $currency_data
     * @throws Exception
     */
    public function updateBillSum(array $currency_data) : void
    {
        $uid = $currency_data['uid'];
        $status = true;
        foreach ($currency_data['currency'] as $currency) {

            // 检测当前类型货币与消费类型是否已存在SUM记录
            $sum_id = $this->where([
                'uid'           => $uid,
                'bill_type_id'  => $currency_data['bill_type_id'],
                'currency_id'   => $currency[0]
            ])->value('id');

            // 不存在则插入
            if (!$sum_id) {
                $data = [
                    'uid' => $uid,
                    'bill_type_id' => $currency_data['bill_type_id'],
                    'currency_id' => $currency[0],
                    'sum' => $currency[1],
                    'lock_sum' => $currency[2]
                ];
                $status = $status && $this->insert($data);
            } else {
                // 存在则更新
                $sum = true;
                $price = true;

                if ($currency[1] !== 0){
                    $sum = $this->where('id',$sum_id)->setInc('sum',$currency[1]);
                }
                if ($currency[2] !== 0){
                    $price = $this->where('id',$sum_id)->setInc('currency_id',$currency[2]);
                }

                $status = $status && $sum && $price;
            }
        }

        if ($status === false) {
            throw new Exception('货币变化总和操作失败', 20005);
        }
    }
}
